<template>
  <div
      class="battle-field"
      @mousemove="handleMouseMove"
      @mousedown="startContinuousShooting"
      @mouseup="stopShooting"
      @mouseleave="stopShooting"
  >
    <!-- 弹坑效果 -->
    <div
        v-for="(crater, index) in craters"
        :key="index"
        class="crater"
        :style="{
        left: crater.x + 'px',
        top: crater.y + 'px',
        transform: `scale(${crater.scale})`
      }"
    ></div>

    <!-- 千束角色 -->
    <div
        class="chisato"
        :style="{
        transform: `translateX(${position.x}px)`,
        transition: isDodging ? 'transform 0.3s' : 'none'
        }"
        @mouseenter="startAiming"
        @mouseleave="stopAiming"
    >
      <img v-if="reactiveImg.status === 0" src="./static/stop.png" alt="千束">
      <img v-else-if="reactiveImg.status === 1" src="./static/right.png" alt="">
      <img v-else src="./static/left.png" alt="">
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'

const chisatoWidth = ref(0)
const aiming = ref(false)
const isDodging = ref(false)
const isShooting = ref(false)
const craters = ref([])
const position = reactive({ x: 0 })
const lastMousePosition = reactive({ x: 0, y: 0 })
let reactiveImg = reactive({ status: 0 })
let shootInterval = null

// 计算当前位置状态
const edgeThreshold = 100 // 距离边缘触发反向闪避的阈值
const isNearLeftEdge = computed(() => position.x < edgeThreshold)
const isNearRightEdge = computed(() => position.x > window.innerWidth - chisatoWidth.value - edgeThreshold)

const mouseRelativePosition = computed(() => {
  const chisatoRect = document.querySelector('.chisato')?.getBoundingClientRect()
  if (!chisatoRect) return 'center'

  const centerX = chisatoRect.left + chisatoRect.width / 2
  return lastMousePosition.x < centerX ? 'left' : 'right'
})

// 初始化位置
onMounted(() => {
  const rect = document.querySelector('.chisato').getBoundingClientRect()
  chisatoWidth.value = rect.width
  position.x = window.innerWidth / 2 - rect.width / 2
})


// 边缘反向修正
function checkTuringBack(dodgeDistance = 0, coverTime = 300){
  if (isNearLeftEdge.value) {
    reactiveImg.status = 1
    dodgeDistance = 200
  }
  if (isNearRightEdge.value) {
    reactiveImg.status = 2
    dodgeDistance = -200
  }

  position.x += dodgeDistance

  setTimeout(() => {
    isDodging.value = false
    reactiveImg.status = 0
  }, coverTime)
}

// 鼠标跟踪逻辑
const handleMouseMove = (e) => {
  lastMousePosition.x = e.clientX
  lastMousePosition.y = e.clientY

  if (isShooting.value) {
    createCrater(e)
  }

  if (!isDodging.value && aiming.value) {
    autoDodge()
  }
}

// 自动躲避算法
const autoDodge = () => {
  const sensitivity = 80
  const chisatoRect = document.querySelector('.chisato').getBoundingClientRect()
  const centerX = chisatoRect.left + chisatoRect.width / 2

  const deltaX = lastMousePosition.x - centerX
  const distance = Math.abs(deltaX)

  if (distance < sensitivity) {
    const moveDirection = deltaX > 0 ? 1 : -1
    position.x -= moveDirection * (sensitivity - distance) * 0.8
  }

  checkTuringBack(undefined, 600)
}

// 持续射击逻辑
const startContinuousShooting = () => {
  isShooting.value = true
  shootInterval = setInterval(() => {
    if (aiming.value) {
      createCrater({ clientX: lastMousePosition.x, clientY: lastMousePosition.y })
    }
    playGunSound()
  }, 100)
}

const stopShooting = () => {
  isShooting.value = false
  clearInterval(shootInterval)
}

const createCrater = (e) => {
  craters.value.push({
    x: e.clientX - 25,
    y: e.clientY - 25,
    scale: Math.random() * 0.6 + 0.4
  })

  if (!isDodging.value && aiming.value) {
    isDodging.value = true

    // 根据鼠标相对位置决定方向
    let dodgeDistance = 0
    if (mouseRelativePosition.value === 'left') {
      dodgeDistance = 150  // 鼠标在左侧时向右闪避
      reactiveImg.status = 1
    } else {
      dodgeDistance = -150 // 鼠标在右侧时向左闪避
      reactiveImg.status = 2
    }

    checkTuringBack(dodgeDistance)

    // 边界限制
    const minX = 0
    const maxX = window.innerWidth - chisatoWidth.value
    position.x = Math.max(minX, Math.min(position.x, maxX))
  }
}

// 准星控制
const startAiming = () => {
  aiming.value = true
}

const stopAiming = () => {
  aiming.value = false
}

// 音频
const shootSound = initAudio()
let audioEnabled = ref(true)

function initAudio() {
  const audio = new Audio('/src/static/oneshot.wav')
  audio.preload = 'auto'
  audio.volume = 0.005
  return audio
}

const playGunSound = () => {
  if (!audioEnabled.value) return

  try {
    const clone = shootSound.cloneNode(true)
    clone.play().catch(handleAudioError)
  } catch (e) {
    handleAudioError(e)
  }
}

const handleAudioError = (error) => {
  console.error('音频错误:', error)
  audioEnabled.value = false
}
</script>

<style scoped>
.battle-field {
  position: fixed;
  width: 100vw;
  height: 100vh;
  background: url('./static/bg.png') center/cover no-repeat;
  overflow: hidden;
}

.crater {
  position: absolute;
  width: 50px;
  height: 50px;
  background: url('./static/hole.png') center/contain no-repeat;
  animation: craterFade 1.5s forwards;
}

.chisato {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94);
  will-change: transform;
}

.chisato img {
  pointer-events: none;
  padding-left: 120px;
  width: 420px;
  height: auto;
  filter: drop-shadow(0 0 15px rgba(255, 100, 100, 0.7));
}

@keyframes craterFade {
  0% { opacity: 1; }
  100% { opacity: 0; }
}
</style>